<?php

namespace Simanx\Spes\Commands;

use Illuminate\Console\Command;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Support\Str;
use Simanx\Spes\Attribute\Route\Permission\PermissionManager;

class PermissionCacheCommand extends Command
{
    protected $signature = 'spes:permission-cache';

    protected $description = '缓存权限';

    public function handle()
    {
        $app = app();
        /** @var PermissionManager $permissionManager */
        $permissionManager = $app->get(PermissionManager::class);
        $permissionTree = $permissionManager->tree();
        $permissionCachePath = $permissionManager->getCachePath();
        $localFs = new Filesystem();
        $localFs->ensureDirectoryExists(Str::beforeLast($permissionCachePath, DIRECTORY_SEPARATOR));
        $localFs->put($permissionCachePath, '<?php return ' . var_export($permissionTree, true) . ';');
        $this->info('权限缓存成功，路径: ' . $permissionCachePath);
    }
}